from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.tools.file_management import ReadFileTool, ListDirectoryTool, FileSearchTool, WriteFileTool
from langchain_core.tools import tool
from langchain_core.messages import ToolMessage, HumanMessage

from langdev_tools.calc import multiply, add, exponentiate
from langdev_tools.search import BingSearchTool
from langdev_tools.file import CwdTool
from langdev_tools.cmd import CmdNode, cmd_condition, State, sense_tools_condition, route_tools

tool = TavilySearchResults(max_results=2)
tools = [
    # tool,
    BingSearchTool(), CwdTool,
    multiply, add, exponentiate,
    ReadFileTool(), ListDirectoryTool(), FileSearchTool(),
]

sense_tools = [
    CwdTool, WriteFileTool()
]

import json
class BasicToolNode:
    """A node that runs the tools requested in the last AIMessage."""

    def __init__(self, tools: list) -> None:
        self.tools_by_name = {tool.name: tool for tool in tools}

    def __call__(self, inputs: dict):
        if messages := inputs.get("messages", []):
            message = messages[-1]
        else:
            raise ValueError("No message found in input")
        outputs = []
        # message.pretty_print()
        for tool_call in message.tool_calls:
            tool_result = self.tools_by_name[tool_call["name"]].invoke(
                tool_call["args"]
            )
            outputs.append(
                ToolMessage(
                    content=json.dumps(tool_result),
                    name=tool_call["name"],
                    tool_call_id=tool_call["id"],
                )
            )
        return {"messages": outputs}




